package com.ketayao.action.admin;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.math.NumberUtils;

import com.ketayao.fensy.mvc.RequestContext;
import com.ketayao.pojo.Album;
import com.ketayao.system.Constants;

/** 
 * @description: 相册
 * @version 1.0
 * @author Kool Zhao
 * @createDate 2014-3-23;上午10:59:23
 */
public class AlbumAction {

	private static final String CREATE = "admin/album/album-create";
	private static final String READ = "admin/album/album-read";
	private static final String UPDATE = "admin/album/album-update";
	private static final String VIEW = "admin/album/album-view";
	
	 @SuppressWarnings("unchecked")
	public String read(RequestContext rc) {
		 List<Album> albums =  (List<Album>) Album.INSTANCE.list("1=1 order by priority asc");
		 rc.getRequest().setAttribute("albums", albums);
		 return READ;
	 }
	 
	 public String preCreate(RequestContext rc) {
		 return CREATE;
	 }
	 
	 public String create(RequestContext rc) throws Exception {
		Album album = new Album();
		BeanUtils.populate(album, rc.getRequest().getParameterMap());
		album.setCreateTime(new Timestamp(System.currentTimeMillis()));
		album.save();
		
		rc.getRequest().setAttribute(Constants.OPERATION_SUCCESS, Constants.OPERATION_SUCCESS);
		return preCreate(rc);
	 }
	 
	 public String delete(RequestContext rc, String[] args) throws Exception {
		 Album album = new Album();
		 album.setId(NumberUtils.toLong(args[0]));
		 album.delete();
			
		 return read(rc);
		}
		
		public String view(RequestContext rc, String[] args) {
			Album album = Album.INSTANCE.get(NumberUtils.toLong(args[0]));
			rc.getRequest().setAttribute("album", album);
			return VIEW;
		}
		
		public String preUpdate(RequestContext rc, String[] args) {
			view(rc, args);
			return UPDATE;
		}
		
		public String update(RequestContext rc) throws IllegalAccessException, InvocationTargetException {
			
			Album album = Album.INSTANCE.get(rc.getId());
			BeanUtils.populate(album, rc.getRequest().getParameterMap());
			
			album.updateAttrs(new String[]{"name", "priority", "description"}, 
					new Object[]{album.getName(), album.getPriority(), album.getDescription()});
			rc.getRequest().setAttribute(Constants.OPERATION_SUCCESS, Constants.OPERATION_SUCCESS);
			rc.getRequest().setAttribute("album", album);
			
			return UPDATE;
		}
}
